TypeScript 3.0 Quick Start Guide by Patrick Desjardins

TypeScript 3.0 Quick Start Guide by Patrick Desjardins

Author:Patrick Desjardins
Language: eng
Format: epub
Tags: COM051260 - COMPUTERS / Programming Languages / JavaScript, COM060090 - COMPUTERS / Internet / Application Development, COM060160 - COMPUTERS / Web / Web Programming
Publisher: Packt Publishing
Published: 2018-08-30T11:00:29+00:00


If you have an interface that you want to build, you can set the variable type with the colon and specify the fields. If a field misses TypeScript will not compile; if there is more than the definition, TypeScript won't compile:

interface MyObject {

a: number;

b: string;

}

const newObject1: MyObject = { a: 1, b: "2" };

Another way is to avoid specifying the type after the colon and use as to cast:

const newObject2 = { a: 1, b: "2" } as MyObject;

The issue is that cast coerces TypeScript to believe the object is the type specified even if it does not respect the contract. Casting should never be used to define a variable. The reason is that even if the contract is respected initially, if the object changes, the cast will still force the type assignation, but the object will not with the right structure. The following two lines compile but are invalid in term of logic. The first one has an additional member that is not in the interface, and the second line is missing one field:

const newObject3 = { a: 1, b: "2", c: "OH NO" } as MyObject;

const newObject4 = { a: 1 } as MyObject;



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.